import {aesEn, aesDe} from "./cryptoUitl"
import conf from "../config/index"
interface tokenInfo {
    ex?: number,
    ip?: string,
    uid: string
}
export function createToken(ti:tokenInfo, key:string = conf.signKey): string {
    if (!ti.ex) ti.ex = new Date().getTime()+2592000000
    const tiStr = JSON.stringify(ti)
    return aesEn(tiStr)
}

interface parseInfo {
    err: string
    ip?: string
    uid: string
}
export function parseToken(token: string, key:string = conf.signKey): parseInfo {
    let ti: tokenInfo
    let tiStr = aesDe(token)
    ti = JSON.parse(tiStr)
    if (new Date().getTime() >= ti.ex) {
        return {
            err: "Token已过期!",
            uid: null
        }
    }
    return {
        err: null,
        ip: ti.ip,
        uid: ti.uid
    }
}
interface refreshInfo {
    err: string
    uid: string
    token: string
}
export function refreshToken(token: string, key:string = conf.signKey): refreshInfo {
    let inf = parseToken(token, key)
    if (inf.err) return {err: inf.err, uid: null, token: null}
    let newToken = createToken({ip: inf.ip,uid: inf.uid}, key)
    return {
        err: null,
        uid: inf.uid,
        token: newToken
    }
}